#include "crud_operations.h"
#include <Poco/Data/RecordSet.h>
#include <Poco/Exception.h>
#include <stdexcept>

using namespace servercom;

CrudOperations::CrudOperations(Poco::Data::Session& session)
    : session_(session) {}

Poco::Data::RecordSet CrudOperations::read(const std::string& table,
                                        const std::vector<std::string>& columns,
                                        const std::string& condition) {
    try {
        std::string sql = "SELECT ";
        for (size_t i = 0; i < columns.size(); ++i) {
            sql += columns[i];
            if (i < columns.size() - 1) sql += ", ";
        }
        sql += " FROM " + table;
        if (!condition.empty()) {
            sql += " WHERE " + condition;
        }

        Poco::Data::Statement select(session_);
        select << sql;
        select.execute();
        return Poco::Data::RecordSet(select);
    } catch (const Poco::Exception& e) {
        throw std::runtime_error("Query failed: " + e.displayText());
    }
}

size_t CrudOperations::update(const std::string& table,
                            const std::vector<std::string>& updates,
                            const std::string& condition) {
    try {
        std::string sql = "UPDATE " + table + " SET ";
        for (size_t i = 0; i < updates.size(); ++i) {
            sql += updates[i];
            if (i < updates.size() - 1) sql += ", ";
        }
        if (!condition.empty()) {
            sql += " WHERE " + condition;
        }

        Poco::Data::Statement update_stmt(session_);
        update_stmt << sql;
        return update_stmt.execute();
    } catch (const Poco::Exception& e) {
        throw std::runtime_error("Update failed: " + e.displayText());
    }
}

size_t CrudOperations::remove(const std::string& table,
                            const std::string& condition) {
    try {
        std::string sql = "DELETE FROM " + table;
        if (!condition.empty()) {
            sql += " WHERE " + condition;
        }

        Poco::Data::Statement delete_stmt(session_);
        delete_stmt << sql;
        return delete_stmt.execute();
    } catch (const Poco::Exception& e) {
        throw std::runtime_error("Delete failed: " + e.displayText());
    }
}